#if  (UNITY_WEBGL || MINIGAME_SUBPLATFORM_WEIXIN) && SEEG_PF_WX

using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEngine;
using WeChatWASM;

namespace ZhiSe.Editor
{
    public class SeegWXBuild
    {
        public static void afterBuildTemplate()
        {
            var cfg = SeegUtil.GetSdkCfg();
            var jumpWechat = false;
            if (cfg.ContainsKey("jumpWX"))
            {
                jumpWechat = (bool)cfg["jumpWX"];
            }
            if (jumpWechat)
            {
                var minigamePath = Path.Combine(BuildTemplateHelper.DstMinigameDir, "game.json");
                if (!File.Exists(minigamePath)) return;
                var gameJson = File.ReadAllText(minigamePath);
                var gameObj = JObject.Parse(gameJson);
                JObject plugins;
                if (gameObj.ContainsKey("plugins"))
                {
                    plugins = (JObject)gameObj["plugins"];
                }
                else
                {
                    gameObj["plugins"] =  plugins  = new JObject();
                }
                if (plugins!.ContainsKey("MiniGameCommon")) return;
                plugins["MiniGameCommon"] = new JObject
                {
                    { "version", "latest" },
                    { "provider", "wxaed5ace05d92b218" },
                    { "contexts", new JArray
                    {
                        new JObject
                        {
                            { "type", "isolatedContext" }
                        }
                    } }
                };
                File.WriteAllText(minigamePath, gameObj.ToString(Formatting.None));
            }

            var tdAppKey = "";
            if (cfg.ContainsKey("tdAppKey"))
            {
                tdAppKey = (string)cfg["tdAppKey"];
            }
            var tdJs = "";
            if (!string.IsNullOrEmpty(tdAppKey))
            {
                tdJs = "require(\"td.js\")";
                var seegPath = Path.GetFullPath("Packages/com.seeg.sdk"); 
                var tdJsPath = Path.Combine(seegPath, "Editor", "Res", "td.js");
                if (!File.Exists(tdJsPath))
                {
                    Debug.LogError($"[SEEG] td.js 文件不存在: {tdJsPath}");
                    return;
                }
                File.Copy(tdJsPath, Path.Combine(BuildTemplateHelper.DstMinigameDir, "td.js"), true);
            }

            var gameJsPath = Path.Combine(BuildTemplateHelper.DstMinigameDir, "game.js");
            var content = File.ReadAllText(gameJsPath);
            content = $"const zsSdkConfig = {cfg};\nGameGlobal.zs = GameGlobal.zs || {{}};\nGameGlobal.zs.gameConfig = zsSdkConfig;\n{tdJs}\n{content}";
            File.WriteAllText(gameJsPath, content);
        }
    }
}

#endif